package com.mymall.serve.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.Set;

/**
 * RestTemplateUtil http请求
 *
 * @author 刘继福
 * @since 2019-09-18
 */
@Slf4j
@Component
public class RestTemplateUtil {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * get请求数据中心
     *
     * @param requestUrl
     * @param tokenName
     * @param tokenValue
     * @param responseClass
     * @param requestParam
     * @param <T>
     * @return
     * @author 魏巍
     * @since 2019/11/17 16:53
     */
    public <T> T getTempDataCenterHttp(String requestUrl, String tokenName, String tokenValue,
                                   Class<T> responseClass, Map<String, Object> requestParam, String hostHead) {
        String requestUrlAll = appendAllRequestUrl(requestUrl, requestParam);
        if (requestParam != null) {
            requestUrl = appendRequestUrl(requestUrl, requestParam.keySet());
        }
        HttpHeaders headers = new HttpHeaders();
        //1、从配置中心获取token
        headers.add(tokenName, tokenValue);
        headers.add("Host",hostHead);
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(null, headers);
        ResponseEntity<T> responseEntity;
        //2、restTemplate请求数据中心api
        try {
            log.info("restTemplate请求，执行getDataCenterHttp方法，requestUrl:{}, requestEntity:{}, requestParam:{}", requestUrl, requestEntity, requestParam);
            responseEntity = restTemplate.exchange(requestUrl, HttpMethod.GET, requestEntity, responseClass, requestParam);
            log.info("request{} response:{}", requestUrlAll, responseEntity);
        } catch (HttpClientErrorException hcex){
            log.error("requestDataCenterHttpClientError:{} ,error:", requestUrlAll, hcex);
            // todo  针对401单独做处理
            throw hcex;
        }catch (Exception e) {
            log.error("requestDataCenterError:{} ,error:{}", requestUrlAll, e);
            // todo 发送告警
            throw e;
        }
        return responseEntity.getBody();
    }

    /**
     * 拼接全部url
     *
     * @param url          地址
     * @param requestParam 参数
     * @return
     */
    public static String appendAllRequestUrl(String url, Map<String, Object> requestParam) {
        if (requestParam == null) {
            return url;
        }

        Set<String> keys = requestParam.keySet();
        if (CollectionUtils.isEmpty(keys)) {
            return url;
        }

        StringBuilder sb = new StringBuilder(url);
        sb.append("?");

        for (Object key : keys) {
            sb.append(key).append("=").append("{").append(requestParam.get(key)).append("}").append("&");
        }
        return sb.deleteCharAt(sb.length() - 1).toString();
    }

    /**
     * 拼接请求url
     *
     * @param url  地址
     * @param keys 参数
     * @return
     */
    public static String appendRequestUrl(String url, Set<String> keys) {
        StringBuilder sb = new StringBuilder(url);
        sb.append("?");

        for (Object key : keys) {
            sb.append(key).append("=").append("{").append(key).append("}").append("&");
        }
        return sb.deleteCharAt(sb.length() - 1).toString();
    }
}
